import { fetchLogin, fetchLogout } from '@/services/login';
import Cookie from 'js-cookie';
import { history } from 'umi';
import { Toast } from 'antd-mobile';

export default {
  namespace: 'login',
  state: {
    tokenMes: {},
  },
  effects: {
    *getLogin({ payload }: any, { call, put }: any): any {
      const response = yield call(fetchLogin, payload);
      if (!response.status) {
        // 登录成功
        yield put({
          type: 'userLogin',
          payload: response,
        });
        Toast.show({
          icon: 'success',
          content: '登录成功',
        });
        history.goBack();
      } else {
        // 登录失败
        Toast.show({
          icon: 'fail',
          content: '登录失败',
        });
      }
    },
    *getLayout(_: any, { put, call }: any): any {
      const response = yield call(fetchLogout);
      if (!response.status) {
        // 退出成功
        yield put({
          type: 'userLogout',
        });
        Toast.show({
          icon: 'success',
          content: '退出成功',
        });
        history.push('/home');
      } else {
        // 退出失败
        Toast.show({
          icon: 'fail',
          content: '退出失败',
        });
      }
    },
  },
  reducers: {
    userLogin(state: any, action: any) {
      const { payload } = action;
      Cookie.set('token', payload.access_token);
      return { ...state, tokenMes: { ...payload } };
    },
    userLogout(state: any) {
      Cookie.remove('token');
      return { ...state, tokenMes: {} };
    },
  },
};
